/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.invoice.busines.dto;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author laura
 */
@FacesConverter(value = "articuloDTOConverter", forClass=ArticuloDTO.class )
public class ArticuloDTOConverter implements Converter {
@Override
public Object getAsObject(FacesContext arg0, UIComponent uiComponent, String value) {
    if(value != null && value.trim().length() > 0) {
            try {
                return (ArticuloDTO) uiComponent.getAttributes().get(value);
            } catch(NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid theme."));
            }
        }
        else {
            return null;
        }
}

@Override
public String getAsString(FacesContext arg0, UIComponent uiComponent, Object value) {
    if(value != null) {
            if (value instanceof ArticuloDTO && ((ArticuloDTO)value).getIdArticulo()!= null) {
                ArticuloDTO articulo = (ArticuloDTO) value;
                uiComponent.getAttributes().put( articulo.getIdArticulo().toString(), articulo);
                return articulo.getIdArticulo().toString();
            }
            return null;
    }
    else {
            return null;
    }
}
}